#include "log.h"

Log::Log()
{
    Common::ConfigureLock.lockForRead();
    Log_Size=Common::Log_Size;
    Common::ConfigureLock.unlock();
    isDirExist(QCoreApplication::applicationDirPath()+"\\"+"LOG");
}

void Log::init(QString Logname)
{
    this->Logname=Logname;
    Savename=QCoreApplication::applicationDirPath()+"\\"+"LOG"+"\\"+Logname+".log";
    oldname=QCoreApplication::applicationDirPath()+"\\"+"LOG"+"\\"+Logname+".old.log";
}

void Log::StartLog()
{
    connect(&logclock,SIGNAL(timeout()),this,SLOT(SaveLog()));
    logclock.start(500);

}

bool Log::isDirExist(QString fullPath)
{
    QDir dir(fullPath);
    if(dir.exists())
    {
        return true;
    }
    else
    {
        bool ok = dir.mkdir(fullPath);//只创建一级子目录，即必须保证上级目录存在
        return ok;
    }
}


void Log::SaveLog()
{
    QStringList logdata;
    Common::LogdataLock.lockForWrite();
    logdata=Common::Logdata;
    Common::Logdata.clear();
    Common::LogdataLock.unlock();
    QFile outputFile(Savename);
    outputFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    QTextStream textStream(&outputFile);
    for(int a=0;a<logdata.size();a++)
    {
        textStream << logdata[a] << endl;
    }
    outputFile.flush();
    outputFile.close();
    QFileInfo fileinfor(outputFile);

   // qDebug()<<fileinfor.size()<<fileinfor.size()/(MB)<<Log_Size;
    if(fileinfor.size()/(MB)>Log_Size)
    {
     QFile deletelog(oldname);
     deletelog.remove();
     qDebug()<<outputFile.rename(Savename,oldname);
    }

}
